//
//  ViewController.swift
//  ElectricBalance
//
//  Created by David on 2016/12/10.
//  Copyright © 2016年 David. All rights reserved.
//

import UIKit

let DOMAIN_NAME = "https://hcdstudio.cn/icard"

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, RoomSelectDelegate{
    
    var tableView: UITableView!
    
    var dorm:[String:String]?
    
    var dormData:[Any]?
    var pickerSelectIndex:[Int] = [0,0,0]
    var dormDetailLabel: UILabel!
    var dormSelBtn: UIButton!
    
    
    var eletrick:Double?
    var eleLabel: UILabel!
    var updateTimeLabel: UILabel!
    var eleSpinner:UIActivityIndicatorView!
    var updateTime: String?
    
    var rechargeInput: UITextField!
    var methodChanger:UISegmentedControl!
    var submitBtn: UIButton!
    
    var rechargeAmount: Double = 100.0
    var payMethod = 0
    
    var loadingView:UIView!
    
    convenience init(list: [Any]){
        self.init()
        dormData = list
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "JLUZH.Ecard"
        
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView(frame: CGRect.zero))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more"), style: .plain, target: self, action: #selector(ViewController.quit))
        print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!)
        
//        let dormJsonStr = NSData(contentsOfFile: Bundle.main.path(forResource: "jluzh_dorm", ofType: "json")!)
//        do{
//            dormData = try JSONSerialization.jsonObject(with: dormJsonStr! as Data, options: .allowFragments) as? [Any]
//        }catch let err{
//            print(err)
//        }

        //MARK:显示宿舍
        dormDetailLabel = UILabel(frame: CGRect(x: view.bounds.width/2, y: 8, width: (view.bounds.width - 32)/2, height: 28))
        dormDetailLabel.textColor = UIColor.gray
        dormDetailLabel.textAlignment = .right
        
        dormSelBtn = UIButton(type: .system)
        dormSelBtn.setTitle("选择宿舍", for: .normal)
        dormSelBtn.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
        dormSelBtn.addTarget(self, action: #selector(ViewController.setDormBtnClick(sender:)), for: .touchUpInside)
        
//        setDormDetail()
        //TODO: 获取本地宿舍信息
        dorm = [:]
        
        
        let build = UserDefaults.standard.object(forKey: "build") as? String
        if build != nil {
            dorm?["build"] = build
            
            let floor = UserDefaults.standard.object(forKey: "floor") as? String
            let room = UserDefaults.standard.object(forKey: "room") as? String
            let name = UserDefaults.standard.object(forKey: "name") as? String
            
            dorm?["floor"] = floor
            dorm?["room"] = room
            dormDetailLabel.text = name
        }else{
            dorm = nil
        }
        
        //显示电量
        eleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 72))
        eleLabel.textAlignment = .center
        
        //显示更新时间
        updateTimeLabel = UILabel(frame: CGRect(x: 0, y: 80, width: view.bounds.width, height: 20))
        updateTimeLabel.textAlignment = .center
        updateTimeLabel.textColor = UIColor.gray
        updateTimeLabel.font = UIFont.systemFont(ofSize: 12)
        
        //加载菊花
        eleSpinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        eleSpinner.center = CGPoint(x: view.center.x - 64, y: updateTimeLabel.center.y)
        
        //电量输入框
        rechargeInput = UITextField(frame: CGRect(x: view.bounds.width/2, y: 8, width: (view.bounds.width-32)/2, height: 28))
        rechargeInput.textAlignment = .right
        rechargeInput.textColor = UIColor.gray
        rechargeInput.text = "100.0"
        rechargeInput.clearButtonMode = .always
        rechargeInput.keyboardType = .decimalPad
        rechargeInput.addTarget(self, action: #selector(ViewController.inputEndEditing(sender:)), for: .editingDidEnd)
//        rechargeInput.addTarget(self, action: #selector(ViewController.inputBeginEditing(sender:)), for: .editingDidBegin)
        
        //支付选择框
        methodChanger = UISegmentedControl(items: ["校园卡","银行卡"])
        methodChanger.frame = CGRect(x: view.bounds.width/2, y: 8, width: (view.bounds.width-32)/2, height: 28)
        methodChanger.selectedSegmentIndex = 0
        methodChanger.addTarget(self, action: #selector(ViewController.methodChanged(sender:)), for: .valueChanged)
        
        //充值按钮
        submitBtn = UIButton(type: .system)
        submitBtn.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
        submitBtn.setTitle("充值", for: .normal)
        submitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        submitBtn.addTarget(self, action: #selector(ViewController.submit), for: .touchUpInside)
        
        tableView = UITableView(frame: view.frame, style: .grouped)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .onDrag
        tableView.allowsSelection = false
        
        //充值加载菊花
        loadingView = UIView(frame: view.frame)
        loadingView.alpha = 0
        view.addSubview(loadingView)
        
        let blackBG = UIView(frame: CGRect(x: 0, y: 0, width: 72, height: 72))
        blackBG.center = view.center
        blackBG.backgroundColor = UIColor(white: 0, alpha: 0.8)
        blackBG.layer.cornerRadius = 8
        loadingView.addSubview(blackBG)
        
        let spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        spinner.center = view.center
        spinner.startAnimating()
        loadingView.addSubview(spinner)
        
        let statuBG = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 20))
        statuBG.backgroundColor = UIColor.groupTableViewBackground
        view.addSubview(statuBG)
        


//        
//        let doneBtn = UIButton(type: .system)
//        doneBtn.frame = CGRect(x: view.bounds.width - 64, y: 8, width: 48, height: 28)
//        doneBtn.setTitle("完成", for: .normal)
//        dormPickerView.addSubview(doneBtn)
//        doneBtn.addTarget(self, action: #selector(ViewController.pickerDidDone(sender:)), for: .touchUpInside)
        
        setEletrick()
        grabEletrick()
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 3
        case 1:
            return 2
        case 2:
            return 1
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 2 {
            return 108
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 1{
            return "电费为0.667元/度，具体以实际为准"
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .value1, reuseIdentifier: "row")
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                cell.textLabel?.text = "宿舍"
                cell.addSubview(dormDetailLabel)
                break
            case 1:
                cell.addSubview(dormSelBtn)
                break
            case 2:
                
                cell.addSubview(eleLabel)
                cell.addSubview(updateTimeLabel)
                cell.addSubview(eleSpinner)
                break
            default:
                break
            }
            break
        case 1:
            switch indexPath.row {
            case 0:
                cell.textLabel?.text = "充值金额(元)"
                
                cell.addSubview(rechargeInput)
                break
            case 1:
                cell.textLabel?.text = "充值方式"
                cell.addSubview(methodChanger)
                break
            default:
                break
            }
            break
        case 2:
            if indexPath.row == 0 {
                cell.addSubview(submitBtn)
            }
            break
        default:
            break
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//        if indexPath.section == 0 && indexPath.row == 0{
//            pickerUpdateToDormLabel()
//            togglePickerView(true)
//        }
    }
    
//    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//        togglePickerView(false)
//    }
//    
//    func inputBeginEditing(sender: UITextField){
//        togglePickerView(false)
//    }
    
    func setDormBtnClick(sender: UIButton){
//        pickerUpdateToDormLabel()
        let selVC = SelectRoomViewController(buildingList: dormData)
        selVC.delegate = self
        navigationController?.pushViewController(selVC, animated: true)
    }
    
//    func setDormDetail(){
//        if dorm?["building"] != nil && dorm?["room"] != nil{
//            dormDetailLabel.text = "\(dorm!["building"]!)\(dorm!["room"]!)"
//        }else{
//            dormDetailLabel.text = "未选择"
//        }
//    }
    
    func setEletrick(){
        eleSpinner.stopAnimating()
        var doubleValueStr = "---.--度"
        updateTimeLabel.text = "请选择宿舍"
        if dorm != nil {
            if eletrick != nil {
                doubleValueStr = String(format: "%0.2lf度", eletrick!)
                updateTimeLabel.text = "抄表时间: "
                if updateTime != nil{
                    updateTimeLabel.text! += updateTime!
                }
                
            }else{
                updateTimeLabel.text = "获取失败"
                
            }
        }
        
        let artStr = NSMutableAttributedString(string: doubleValueStr)
        artStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 48), range: NSMakeRange(0, artStr.length - 1))
        
        eleLabel.attributedText = artStr
    }
    
    func grabEletrick(){
        //TODO: 获取电量
        if dorm != nil {
            updateTimeLabel.text = "正在获取..."
            eleSpinner.startAnimating()
            let build = dorm!["build"]
            let floor = dorm!["floor"]
            let room = dorm!["room"]
            if build != nil && floor != nil && room != nil {
                var resq = URLRequest(url: URL(string: "\(DOMAIN_NAME)/getBalance.php")!)
                resq.httpMethod = "POST"
                resq.httpBody = "building=\(build!)&floor=\(floor!)&room=\(room!)".data(using: .utf8)
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                    if err == nil {
                        if data != nil {
                            let str = String(data: data!, encoding: .utf8)
                            
                            if str != nil {
                                print(str!)
                                let compo = str!.components(separatedBy: ",")
                                if compo.count >= 2{
                                    self.eletrick = Double(compo[0])
                                    self.updateTime = compo[1]
                                    
                                }
                                DispatchQueue.main.async {
                                    self.setEletrick()
                                }
                            }
                        }
                    }
                }).resume()
            }
            
        }else{
            dormDetailLabel.text = "未选择"
            updateTimeLabel.text = "请选择宿舍"
        }
        
    }
    
    //控制输入
    func inputEndEditing(sender: UITextField){
        let amount = Double(sender.text!)
        if amount != nil{
            if amount! > 0{
                rechargeAmount = amount!
            }else{
                rechargeAmount = 1.0
            }
            
        }else{
            rechargeAmount = 1.0
        }
        sender.text = String(format: "%0.1lf", rechargeAmount)
    }
    
    //选择支付方式
    func methodChanged(sender: UISegmentedControl){
        payMethod = sender.selectedSegmentIndex
    }
    
    func submit(){
        
        rechargeInput.resignFirstResponder()
        
        if dorm == nil{
            let alert = UIAlertController(title: "请选择宿舍", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
            return
        }
        
        //TODO: 提交充值请求
        let alert = UIAlertController(title: "暂不支持充电费功能，敬请期待", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
        return
        
        
//        loadingView.alpha = 1
//        if #available(iOS 10.0, *) {
//            Timer.scheduledTimer(withTimeInterval: 5, repeats: false, block: {(Timer) -> Void in
//                self.loadingView.alpha = 0
//                let alert = UIAlertController(title: nil, message: "宿舍: \(self.dorm!["building"]!)\(self.dorm!["room"]!)\n金额: \(self.rechargeAmount)\n方式: \(self.payMethod)", preferredStyle: .alert)
//                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
//                self.present(alert, animated: true, completion: nil)
//                
//                UserDefaults.standard.setValue(self.dorm, forKey: "dorm")
//                UserDefaults.standard.setValue(self.pickerSelectIndex, forKey: "selectIndex")
//            })
//        } else {
//            // Fallback on earlier versions
//        }
        
    }
    
    func didFinishSelectRoom(vc: SelectRoomViewController) {
        dormDetailLabel.text = "\(vc.dormName!)\(vc.roomName!)"
        dorm = [:]
        dorm?["build"] = vc.selectedBuildID
        dorm?["floor"] = vc.selectedFloorID
        dorm?["room"] = vc.selectedRoomID
        grabEletrick()
    }
    
    func quit(){
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "退出登陆", style: .default, handler: { (action) in
            _ = self.navigationController?.popViewController(animated: true)
        }))
        alert.addAction(UIAlertAction(title: "退出并清除账号", style: .destructive, handler: { (action) in
            UserDefaults.standard.removeObject(forKey: "uname")
            UserDefaults.standard.removeObject(forKey: "psw")
            UserDefaults.standard.removeObject(forKey: "build")
            UserDefaults.standard.removeObject(forKey: "floor")
            UserDefaults.standard.removeObject(forKey: "room")
            UserDefaults.standard.removeObject(forKey: "name")
            _ = self.navigationController?.popViewController(animated: true)
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}
